import 'dotenv/config'
import express from 'express'
import cors from 'cors'
import mysql from 'mysql2/promise'
import bcrypt from 'bcryptjs'

const app = express()
app.use(cors())
app.use(express.json())

const dbConfig = {
  host: process.env.DB_HOST || '127.0.0.1',
  port: Number(process.env.DB_PORT || 3306),
  user: process.env.DB_USER || 'root',
  password: process.env.DB_PASSWORD || '123456',
  database: process.env.DB_NAME || 'music-min',
  connectionLimit: 10
}

const pool = mysql.createPool(dbConfig)

app.get('/api/health', async (_req, res) => {
  try {
    const [rows] = await pool.query('SELECT 1 AS ok')
    res.json({ status: 'ok', db: rows[0].ok === 1 })
  } catch (err) {
    res.status(500).json({ status: 'error', message: String(err?.message || err) })
  }
})

// 显示表结构和数据（调试用）
app.get('/api/debug/tables', async (_req, res) => {
  try {
    // 显示 users 表结构
    const [usersSchema] = await pool.query('DESCRIBE users')
    // 显示 users 表数据
    const [usersData] = await pool.query('SELECT id, username, nickname, avatar, email, status, created_at FROM users ORDER BY id DESC LIMIT 10')
    // 显示 music 表数据
    const [musicData] = await pool.query('SELECT id, title, artist, cover, duration, status FROM music ORDER BY id DESC LIMIT 5')
    // 显示 banners 表数据
    const [bannersData] = await pool.query('SELECT id, title, image, link, sort_order, status, created_at FROM banners ORDER BY sort_order ASC')
    
    res.json({
      users_schema: usersSchema,
      users_data: usersData,
      music_data: musicData,
      banners_data: bannersData,
      db_config: {
        host: dbConfig.host,
        port: dbConfig.port,
        database: dbConfig.database,
        user: dbConfig.user
      }
    })
  } catch (err) {
    res.status(500).json({ status: 'error', message: String(err?.message || err) })
  }
})

// 注册
app.post('/api/auth/register', async (req, res) => {
  const { username, password, nickname, avatar } = req.body || {}
  if (!username || !password || !nickname) return res.status(400).json({ message: 'missing fields' })
  try {
    const salt = bcrypt.genSaltSync(10)
    const hash = bcrypt.hashSync(password, salt)
    const defaultAvatar = avatar || 'https://ai-public.mastergo.com/ai/img_res/4f8c61af426b6e29d3c0f5ce2f9e1f66.jpg'
    
    // 判断是邮箱还是手机号
    const isEmail = username.includes('@')
    const email = isEmail ? username : null
    
    const [ret] = await pool.query(
      'INSERT INTO users (username, password, nickname, avatar, email, status) VALUES (?, ?, ?, ?, ?, 1)',
      [username, hash, nickname, defaultAvatar, email]
    )
    const insertId = ret && ret.insertId ? Number(ret.insertId) : 0
    let userRow = null
    if (insertId) {
      const [rows] = await pool.query('SELECT id, username, nickname, avatar, email FROM users WHERE id = ?', [insertId])
      userRow = rows && rows[0] ? rows[0] : null
    }
    res.json({ ok: true, id: insertId, user: userRow })
  } catch (err) {
    // 处理唯一键冲突
    if (String(err?.code) === 'ER_DUP_ENTRY') {
      return res.status(409).json({ message: 'username already exists' })
    }
    res.status(500).json({ message: String(err?.message || err) })
  }
})

// 登录（返回简易用户信息，不做 token，示例用）
app.post('/api/auth/login', async (req, res) => {
  const { username, password } = req.body || {}
  if (!username || !password) return res.status(400).json({ message: 'missing fields' })
  try {
    // 支持邮箱或手机号登录
    const [rows] = await pool.query('SELECT id, username, password, nickname, avatar, email, status FROM users WHERE username = ? OR email = ?', [username, username])
    if (!rows.length) return res.status(401).json({ message: 'invalid credentials' })
    const user = rows[0]
    const ok = bcrypt.compareSync(password, user.password)
    if (!ok) return res.status(401).json({ message: 'invalid credentials' })
    res.json({ id: user.id, username: user.username, nickname: user.nickname, avatar: user.avatar, email: user.email })
  } catch (err) {
    res.status(500).json({ message: String(err?.message || err) })
  }
})

// 用户统计
app.get('/api/users/:userId/stats', async (req, res) => {
  const userId = Number(req.params.userId)
  if (!userId) return res.status(400).json({ message: 'invalid userId' })
  try {
    const [favRows] = await pool.query('SELECT COUNT(*) AS c FROM favorites WHERE user_id = ?', [userId])
    const [histRows] = await pool.query('SELECT COUNT(*) AS c FROM play_history WHERE user_id = ?', [userId])
    const favorites = favRows && favRows[0] ? Number(favRows[0].c) : 0
    const history = histRows && histRows[0] ? Number(histRows[0].c) : 0
    res.json({ favorites, history, downloads: 0 })
  } catch (err) {
    res.status(500).json({ message: String(err?.message || err) })
  }
})

// 获取用户资料
app.get('/api/users/:userId', async (req, res) => {
  const userId = Number(req.params.userId)
  if (!userId) return res.status(400).json({ message: 'invalid userId' })
  try {
    const [rows] = await pool.query('SELECT id, username, nickname, avatar, email, status, created_at FROM users WHERE id = ?', [userId])
    if (!rows.length) return res.status(404).json({ message: 'not found' })
    res.json(rows[0])
  } catch (err) {
    res.status(500).json({ message: String(err?.message || err) })
  }
})

// 更新用户资料（昵称、头像、邮箱）
app.put('/api/users/:userId', async (req, res) => {
  const userId = Number(req.params.userId)
  const { nickname, avatar, email } = req.body || {}
  if (!userId) return res.status(400).json({ message: 'invalid userId' })
  try {
    await pool.query('UPDATE users SET nickname = COALESCE(?, nickname), avatar = COALESCE(?, avatar), email = COALESCE(?, email) WHERE id = ?', [nickname ?? null, avatar ?? null, email ?? null, userId])
    res.json({ ok: true })
  } catch (err) {
    res.status(500).json({ message: String(err?.message || err) })
  }
})
// 轮播图接口
app.get('/api/banners', async (_req, res) => {
  try {
    const [rows] = await pool.query('SELECT id, title, image, link, sort_order FROM banners WHERE status = 1 ORDER BY sort_order ASC')
    res.json(rows)
  } catch (err) {
    res.status(500).json({ message: String(err?.message || err) })
  }
})

// 添加轮播图接口
app.post('/api/banners', async (req, res) => {
  const { title, image, link, sort_order } = req.body || {}
  if (!title || !image) return res.status(400).json({ message: 'title and image are required' })
  try {
    const [result] = await pool.query(
      'INSERT INTO banners (title, image, link, sort_order, status) VALUES (?, ?, ?, ?, 1)',
      [title, image, link || '', sort_order || 1]
    )
    res.json({ ok: true, id: result.insertId })
  } catch (err) {
    res.status(500).json({ message: String(err?.message || err) })
  }
})

// 图片上传接口
app.post('/api/upload', async (req, res) => {
  try {
    // 这里需要安装 multer 来处理文件上传
    // npm install multer
    res.json({ message: '图片上传功能需要安装multer依赖' })
  } catch (err) {
    res.status(500).json({ message: String(err?.message || err) })
  }
})

app.get('/api/music', async (req, res) => {
  const q = (req.query.q || '').toString().trim()
  try {
    let sql = 'SELECT id, title, artist, cover, duration FROM music'
    const params = []
    if (q) {
      sql += ' WHERE title LIKE ? OR artist LIKE ?'
      const like = `%${q}%`
      params.push(like, like)
    }
    sql += ' ORDER BY id DESC LIMIT 100'
    const [rows] = await pool.query(sql, params)
    res.json({ items: rows })
  } catch (err) {
    res.status(500).json({ message: String(err?.message || err) })
  }
})

// 音乐详情（含更多字段）
app.get('/api/music/:id', async (req, res) => {
  const id = Number(req.params.id)
  if (!id) return res.status(400).json({ message: 'invalid id' })
  try {
    const [rows] = await pool.query(
      'SELECT id, title, artist, album, cover, src, duration, genre, lyrics, play_count, like_count, created_at FROM music WHERE id = ? AND status = 1',
      [id]
    )
    if (!rows.length) return res.status(404).json({ message: 'not found' })
    res.json(rows[0])
  } catch (err) {
    res.status(500).json({ message: String(err?.message || err) })
  }
})

// 用户收藏列表
app.get('/api/users/:userId/favorites', async (req, res) => {
  const userId = Number(req.params.userId)
  if (!userId) return res.status(400).json({ message: 'invalid userId' })
  try {
    const [rows] = await pool.query(
      `SELECT m.id, m.title, m.artist, m.cover, m.duration, f.created_at as favorite_time
       FROM favorites f JOIN music m ON f.music_id = m.id
       WHERE f.user_id = ? AND m.status = 1
       ORDER BY f.created_at DESC LIMIT 200`,
      [userId]
    )
    res.json({ items: rows })
  } catch (err) {
    res.status(500).json({ message: String(err?.message || err) })
  }
})

// 添加收藏
app.post('/api/users/:userId/favorites', async (req, res) => {
  const userId = Number(req.params.userId)
  const musicId = Number(req.body?.music_id)
  if (!userId || !musicId) return res.status(400).json({ message: 'userId or music_id missing' })
  try {
    await pool.query('INSERT IGNORE INTO favorites (user_id, music_id) VALUES (?, ?)', [userId, musicId])
    res.json({ ok: true })
  } catch (err) {
    res.status(500).json({ message: String(err?.message || err) })
  }
})

// 取消收藏
app.delete('/api/users/:userId/favorites/:musicId', async (req, res) => {
  const userId = Number(req.params.userId)
  const musicId = Number(req.params.musicId)
  if (!userId || !musicId) return res.status(400).json({ message: 'invalid params' })
  try {
    await pool.query('DELETE FROM favorites WHERE user_id = ? AND music_id = ?', [userId, musicId])
    res.json({ ok: true })
  } catch (err) {
    res.status(500).json({ message: String(err?.message || err) })
  }
})

// 播放历史列表
app.get('/api/users/:userId/history', async (req, res) => {
  const userId = Number(req.params.userId)
  if (!userId) return res.status(400).json({ message: 'invalid userId' })
  try {
    const [rows] = await pool.query(
      `SELECT ph.id, ph.play_time, ph.play_duration, m.id AS music_id, m.title, m.artist, m.cover, m.duration
       FROM play_history ph JOIN music m ON ph.music_id = m.id
       WHERE ph.user_id = ?
       ORDER BY ph.play_time DESC LIMIT 200`,
      [userId]
    )
    res.json({ items: rows })
  } catch (err) {
    res.status(500).json({ message: String(err?.message || err) })
  }
})

// 追加播放历史
app.post('/api/users/:userId/history', async (req, res) => {
  const userId = Number(req.params.userId)
  const musicId = Number(req.body?.music_id)
  const playDuration = Number(req.body?.play_duration || 0)
  if (!userId || !musicId) return res.status(400).json({ message: 'userId or music_id missing' })
  try {
    await pool.query('INSERT INTO play_history (user_id, music_id, play_duration) VALUES (?, ?, ?)', [userId, musicId, playDuration])
    res.json({ ok: true })
  } catch (err) {
    res.status(500).json({ message: String(err?.message || err) })
  }
})

// 删除播放历史
app.delete('/api/users/:userId/history/:historyId', async (req, res) => {
  const userId = Number(req.params.userId)
  const historyId = Number(req.params.historyId)
  if (!userId || !historyId) return res.status(400).json({ message: 'userId or historyId missing' })
  try {
    const [result] = await pool.query('DELETE FROM play_history WHERE id = ? AND user_id = ?', [historyId, userId])
    if (result.affectedRows === 0) {
      return res.status(404).json({ message: '播放历史不存在' })
    }
    res.json({ ok: true })
  } catch (err) {
    res.status(500).json({ message: String(err?.message || err) })
  }
})

// 清空用户所有播放历史
app.delete('/api/users/:userId/history', async (req, res) => {
  const userId = Number(req.params.userId)
  if (!userId) return res.status(400).json({ message: 'userId missing' })
  try {
    const [result] = await pool.query('DELETE FROM play_history WHERE user_id = ?', [userId])
    res.json({ ok: true, deletedCount: result.affectedRows })
  } catch (err) {
    res.status(500).json({ message: String(err?.message || err) })
  }
})

const port = Number(process.env.PORT || 3001)
app.listen(port, () => {
  console.log(`API listening on http://localhost:${port}`)
})


